package com.crane.common.core.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: zhenxing.pi
 * @Date: 2020/7/8 15:37
 */
public class Md5Util {

    public static String encodeBase64(String s) {
        if (s == null) {
            return null;
        }
        return (new BASE64Encoder()).encode(s.getBytes());
    }

    public static String encodeBase64(byte[] b) {
        if (b == null || b.length == 0) {
            return null;
        }
        return (new BASE64Encoder()).encode(b);
    }

    public static String decodeBase64(String s) {
        if (s == null) {
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static byte[] md5(String source) {
        byte[] result = new byte[16];
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        result = messageDigest.digest(source.getBytes());
        return result;
    }

    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public static String md5EncodeBase64(String source) {
        byte[] result = md5(source);
        if (result == null) {
            return null;
        }
        String ret = encodeBase64(result);
        return ret;
    }

    public static void main(String[] args) {
        String username = "19873763344";
        String sKey = "123456" + username.substring(username.length() - 5);
        System.out.println(md5EncodeBase64(sKey));
    }
}
